import request from '@/utils/request'
import type { PageResponse } from '@/types'
import type { ExamStatistics, ScoreDistribution } from '@/types/statistics'

export interface ExamRecord {
  id: number
  examId: number
  examTitle: string
  userId: number
  username: string
  fullName: string
  startTime: string
  endTime?: string
  duration: number
  score?: number
  totalScore: number
  status: 'IN_PROGRESS' | 'COMPLETED' | 'TIMEOUT' | 'ABANDONED'
  answers: ExamAnswer[]
  createdAt: string
}

export interface ExamAnswer {
  questionId: number
  answer: string
  isCorrect?: boolean
  score?: number
}

export interface ExamRecordQuery {
  page: number
  size: number
  examId?: number
  userId?: number
  username?: string
  status?: string
  startTime?: string
  endTime?: string
}

/**
 * 考试记录API接口
 */
export const examRecordApi = {
  /**
   * 获取考试记录列表
   * @param params 查询参数
   */
  getExamRecords: (params: ExamRecordQuery) =>
    request.get<PageResponse<ExamRecord>>('/exam-records', { params }),

  /**
   * 获取考试记录详情
   * @param id 记录ID
   */
  getExamRecord: (id: number) =>
    request.get<ExamRecord>(`/exam-records/${id}`),

  /**
   * 开始考试
   * @param examId 考试ID
   */
  startExam: (examId: number) =>
    request.post<ExamRecord>(`/exam-records/start/${examId}`),

  /**
   * 提交答案
   * @param recordId 记录ID
   * @param answers 答案列表
   */
  submitAnswers: (recordId: number, answers: ExamAnswer[]) =>
    request.post<ExamRecord>(`/exam-records/${recordId}/submit`, { answers }),

  /**
   * 完成考试
   * @param recordId 记录ID
   */
  finishExam: (recordId: number) =>
    request.post<ExamRecord>(`/exam-records/${recordId}/finish`),

  /**
   * 获取用户的考试记录
   * @param params 查询参数
   */
  getMyExamRecords: (params: Omit<ExamRecordQuery, 'userId'>) =>
    request.get<PageResponse<ExamRecord>>('/exam-records/my', { params }),

  /**
   * 获取考试统计信息
   * @param examId 考试ID
   */
  getExamStatistics: (examId: number) =>
    request.get<ExamStatistics>(`/exam-records/statistics/${examId}`)
}